export default {
	namespaced:true,
	
	state:()=>({
		// 直接从内存中读取
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	
	mutations:{
		addToCart(state,goods){
			const findResult = state.cart.find(x=>x.goods_id === goods.goods_id)
			
			if(!findResult){
				state.cart.push(goods)
			}else{
				findResult.goods_count++
			}
			
			// 自己调用自己的数据 记住       购物车添加或者增加数量的时候就直接存到内存
			this.commit('my_cart/saveToStorage')
		},
		// 持久化存储购物车中的商品
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		// 更新购物车商品的勾选状态
		updateGoodsState(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_state = goods.goods_state
				// 再在本地保存勾选状态
				this.commit('my_cart/saveToStorage')
			}
		},
		updateGoodsCount(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_count = goods.goods_count
			}
			// 再在本地保存勾选状态
			this.commit('my_cart/saveToStorage')
		},
		// 根据id删除对应的商品
		removeGoodsById(state,goods_id){
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			// 再在本地保存勾选状态
			this.commit('my_cart/saveToStorage')
		},
		// 更新购物车中所有商品的勾选状态
		updateAllGoodsState(state,newState){
			state.cart.forEach(x => x.goods_state = newState)
			// 再在本地保存勾选状态
			this.commit('my_cart/saveToStorage')
		}
	},
	
	getters:{
		// 购物车所有的总数量
		total(state){
			// let c = 0
			// state.cart.foreach(x=>c += x.goods_count)
			// return c
			// 改造计算方式
			return state.cart.reduce((total,item)=>total += item.goods_count,0)
		},
		// 已勾选商品的总数量
		checkedCount(){
			return state.cart.filter(x => x.goods_state).reduce((total,item)=>total += item.goods_count,0)
		},
		// 已勾选商品的总价格
		checkGoodsAmount(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item)=>total += item.goods_count * item.goods_price,0).toFix(2)
		}
	}
}